package com.javatest.springboot3minio.service;

import com.javatest.springboot3minio.dao.AttachmentManageDao;
import com.javatest.springboot3minio.entity.AttachmentInfo;
import com.javatest.springboot3minio.utils.MinioFileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created with IntelliJ IDEA. Description:
 *
 * @author lzy
 * @since 2024-01-12 下午1:35
 */
@Service
public class AttachmentManageServiceImpl implements AttachmentManageService {
  private AttachmentManageDao attachmentManageDao;

  @Autowired
  public void setAttachmentManageDao(AttachmentManageDao attachmentManageDao) {
    this.attachmentManageDao = attachmentManageDao;
  }

  /**
   * @param projectId the project id
   * @param attachmentType the attachment type
   * @param file the file
   * @return
   */
  @Override
  public boolean uploadAttachment(String projectId, String attachmentType, MultipartFile file) {
    AttachmentInfo attachmentInfo =
        AttachmentInfo.builder()
            .withAttachmentName(file.getOriginalFilename())
            .withAttachmentType(attachmentType)
            .withProjectId(projectId)
            .build();
    // 如果数据库中已经有该附件，则直接上传文件
    if (attachmentManageDao.countAttachment(attachmentInfo) > 0) {
      String result = MinioFileUtil.uploadFile(projectId, file);
      return StringUtils.isNotBlank(result);
    } else {
      if (attachmentManageDao.addNewAttachment(attachmentInfo) > 0) {
        String result = MinioFileUtil.uploadFile(projectId, file);
        return StringUtils.isNotBlank(result);
      }
    }
    return false;
  }
}
